import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
  },
  onLoad(query) {
    this.query = query
    console.log(query)
  },
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请输入正确的手机号!' },
    ],
    code: [
      { required: true, message: '请填写短信验证码!' },
      { pattern: /^\d{6}$/, message: '请检查短信验证码是否正确!' },
    ],
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  async getMsg() {
    const { valid, message } = this.validate('mobile')
    if (valid) {
      const res = await wx.http.get('/code', { mobile: this.data.mobile })
      if (res.code === 10000) {
        console.log(res.data.code)
        this.setData({
          countDownVisible: true,
        })
      }
    } else {
      wx.utils.toast(message)
    }
  },
  async login() {
    const valid = this.validate()
    if (valid) {
      const res = await wx.http({
        url: '/login',
        method: 'post',
        data: {
          mobile: this.data.mobile,
          code: this.data.code,
        },
      })
      if (res.code === 10000) {
        getApp().setToken('token', res.data.token)
        getApp().setToken('refreshToken', res.data.refreshToken)
        wx.redirectTo({
          url: this.query.redirectUrl,
        })
      }
    } else {
      wx.utils.toast('请检查输入是否正确!')
    }
  },
})
